//
//  MSUploadCardViewController.m
//  SocietySale
//
//  Created by Mike on 16/11/3.
//  Copyright © 2016年 Mike. All rights reserved.
//

#import "MSUploadCardViewController.h"
#import "MSUploadCardTableVC.h"
#import "MSRegistSuccessViewController.h"

@interface MSUploadCardViewController ()<UIAlertViewDelegate>
@property (nonatomic, assign) NSInteger           cellIndex;
@property (nonatomic, strong) GXButton            *doneBtn;
@property (nonatomic, strong) MSUploadCardTableVC *tableVC;
@property (nonatomic, strong) UIActionSheet       *uploadPhotoActionSheet;
@end

@implementation MSUploadCardViewController

- (void)initNavigationBar{
    [super initNavigationBar];
    leftBarBtn.hidden = NO;
    rightBarBtn.hidden = NO;
    [rightBarBtn setTitle:@"跳过" forState:UIControlStateNormal];
    [rightBarBtn setTitleColor:kCyanColor forState:UIControlStateNormal];
    rightBarBtn.titleLabel.font = HeitiFont(14);
    titleLable.text = @"上传名片";
}

- (void)rightBarBtnAction{
    MSUploadModel *model = self.tableVC.dataArray[0];
    MSUploadModel *model2 = self.tableVC.dataArray[1];
    if (model.haveUpload || model2.haveUpload) {
        if (self.isRegist) {
            //            [rootNavigation popToRootViewControllerAnimated:NO];
        }
        else{
            //            [rootNavigation popViewControllerAnimated:YES];
        }
    }
    else{//一张都没有
        
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"名片未上传" message:@"为创造真实有效的共享环境，本平台只接受上传名片注册，如果选择跳过，核心功能无法使用" delegate:self cancelButtonTitle:@"返回上传" otherButtonTitles:@"跳过暂不上传",nil];
    alertView.tag = 20;
    [alertView show];
}

- (void)initUI{
    self.tableVC = [[MSUploadCardTableVC alloc] initWithStyle:UITableViewStyleGrouped];
    self.tableVC.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-KNavBarHeight);
    self.tableVC.enableRefresh = NO;
    self.tableVC.enableRequest = NO;
    self.tableVC.delegate = (id)self;
    self.tableVC.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:self.tableVC.view];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
    headerView.backgroundColor = kDefaultViewBackgroundColor;
    self.tableVC.tableView.tableHeaderView = headerView;
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, 290, 60)];
    titleLabel.text = @"上传名片有助于真是共享，获得业务合作机遇哦";
    titleLabel.textColor = UIColorFromRGB(0x222222);
    titleLabel.font = HeitiFont(13);
    [headerView addSubview:titleLabel];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    footerView.backgroundColor = kDefaultViewBackgroundColor;
    self.tableVC.tableView.tableFooterView = footerView;
    
//    UIView *horizonLineView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.6)];
//    horizonLineView.backgroundColor = kNormalGray;
//    [footerView addSubview:horizonLineView];
    
    self.doneBtn = [[GXButton alloc] initWithFrame:CGRectMake(12, 15, SCREEN_WIDTH-24, 45)];
    self.doneBtn.titleLabel.font = HeitiFont(16);
    [self.doneBtn setTitle:@"完成" forState:UIControlStateNormal];
    [self.doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.doneBtn.backgroundColor = kBlueColor;
    self.doneBtn.layer.cornerRadius = 2;
    [self.doneBtn addTarget:self action:@selector(doneClick) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:self.doneBtn];
}

- (void)testDataFunc{
    MSUploadModel *model = [[MSUploadModel alloc] init];
    model.title = @"请您上传名片正面照";
    model.subTitle = @"【示例图】";
    model.exampleImage = @"card1";
    model.officialImage = @"";
    model.haveUpload = NO;
    
    MSUploadModel *model2 = [[MSUploadModel alloc] init];
    model2.title = @"请您上传名片背面照";
    model2.subTitle = @"【示例图】";
    model2.exampleImage = @"card2";
    model2.officialImage = @"";
    model2.haveUpload = NO;
    
    self.tableVC.dataArray = [@[model,model2] mutableCopy];
}

- (void)updateViewController:(NSNotification *)note {
    NSDictionary *responseDic = note.userInfo;
    if (responseDic[Receiver]==self.VctrID) {
        if (responseDic[@"UploadImage"]!=nil){
            NSMutableArray *imageId = [NSMutableArray arrayWithCapacity:0];
            NSArray *pictureArray = responseDic[@"UploadImage"];
            for (propertyPicture *pictureModel in pictureArray) {
                [imageId addObject:[HDUtil check:pictureModel.cateId]];
            }
            NSString *frontImgId = @"";
            NSString *backImgId = @"";
            if (pictureArray.count>0) {
                propertyPicture *pictureModel = pictureArray[0];
                frontImgId = pictureModel.cateId;
            }
            if (pictureArray.count>1) {
                propertyPicture *pictureModel = pictureArray[1];
                backImgId = pictureModel.cateId;
            }
            NSDictionary *params = @{@"cardFrontImgId":frontImgId,
                                     @"cardBackImgId":backImgId};
            [netEngine requestUploadCardUrlWithTarget:self.VctrID hudView:self.contentView params:params];
        }
        if (responseDic[@"UploadCard"]!=nil){
            if (self.isRegist) {
                MSRegistSuccessViewController *vc = [[MSRegistSuccessViewController alloc] init];
                [rootNavigation pushViewController:vc animated:YES];
            }
            else{
                [rootNavigation popViewControllerAnimated:YES];
            }
        }
    }
}

- (void)doneClick{
    MSUploadModel *model = self.tableVC.dataArray[0];
    MSUploadModel *model2 = self.tableVC.dataArray[1];
    if (model.haveUpload || model2.haveUpload) {
        NSArray *imageArray;
        if (model.haveUpload && model2.haveUpload) {
            imageArray = @[model.selectImage,model2.selectImage];
        }
        else{
            if (model.haveUpload){
                imageArray = @[model.selectImage];
            }
            if (model2.haveUpload){
                imageArray = @[model2.selectImage];
            }
        }
//        NSData *data=[NSJSONSerialization dataWithJSONObject:imageArray options:NSJSONWritingPrettyPrinted error:nil];
//        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [netEngine requestUploadImageWithTarget:self.VctrID hudView:self.contentView params:imageArray];
    }
    else{//一张都没有
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"名片未上传" message:@"为创造真实有效的共享环境，本平台只接受上传名片注册，如果选择跳过，核心功能无法使用" delegate:self cancelButtonTitle:@"返回上传" otherButtonTitles:@"跳过暂不上传",nil];
        alertView.tag = 20;
        [alertView show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        if (self.isRegist) {
            [rootNavigation popToRootViewControllerAnimated:NO];
        }
        else{
            [rootNavigation popViewControllerAnimated:YES];
        }
    }
}

- (void)reloadTableViewWithImage:(UIImage*)image{
    MSUploadModel *model = self.tableVC.dataArray[self.cellIndex];
    model.haveUpload = YES;
    model.selectImage = image;
    [self.tableVC.tableView reloadData];
}

- (void)clickCellIndex:(NSInteger)index{
    NSLog(@"%ld",index);
    self.cellIndex = index;
    [self createActionSheet];
}

#pragma mark - actionSheet
- (void)createActionSheet {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        self.uploadPhotoActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:(id)self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍摄",@"从相册选择",nil];
    }else {
        self.uploadPhotoActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:(id)self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从手机相册选择", nil];
    }
    self.uploadPhotoActionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    self.uploadPhotoActionSheet.delegate = (id)self;
    [self.uploadPhotoActionSheet showInView:self.view];
}

#pragma mark -actionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == actionSheet.cancelButtonIndex) {

    }
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {
            case 0:
            {
                [self takePhoto];
            }
                break;
            case 1:
            {
                [self openLocalAlbum];
            }
                break;
            default:
                break;
        }
    }
    else
    {
        switch (buttonIndex) {
            case 0:
            {
                [self openLocalAlbum];
            }
                break;
            default:
                break;
        }
    }
}

#pragma mark -takePhoto
- (void)takePhoto {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = (id)self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = sourceType;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }else {
        NSLog(@"模拟器无法调用相机");
    }
}

#pragma mark - openLocalAlbum
- (void)openLocalAlbum {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = (id)self;
    imagePicker.allowsEditing = YES;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark - pickerViewControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    //        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];//原始图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];//裁剪后图片
    [self reloadTableViewWithImage:image];
    [self dismissViewControllerAnimated:YES completion:nil];
//    [netEngine requestModifyheadImageInfoWithTarget:self.VctrID hudView:self.contentView image:image];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
